05. 练习:TensorFlow 数学
TensorFlow 数学
获取输入很棒,但是现在你需要使用它。你将使用每个人都懂的基础数学运算,加、减、乘、除,来处理 tensor。(更多数学函数请查看文档)。
加法
x = tf.add(5, 2) # 7
从加法开始,tf.add()
函数如你所想,它传入两个数字、两个 tensor、或数字和 tensor 各一个,以 tensor 的形式返回它们的和。
减法和乘法
这是减法和乘法的例子:
x = tf.subtract(10, 4) # 6
y = tf.multiply(2, 5) # 10
x
tensor 求值结果是 6
,因为 10 - 4 = 6
。y
tensor 求值结果是 10
,因为 2 * 5 = 10
。是不是很简单!
类型转换
为了让特定运算能运行,有时会对类型进行转换。例如,你尝试下列代码,会报错:
tf.subtract(tf.constant(2.0),tf.constant(1)) # Fails with ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int32:
这是因为常量 1
是整数,但是常量 2.0
是浮点数,subtract
需要它们的类型匹配。
在这种情况下,你可以确保数据都是同一类型,或者强制转换一个值为另一个类型。这里,我们可以把 2.0
转换成整数再相减,这样就能得出正确的结果:
tf.subtract(tf.cast(tf.constant(2.0), tf.int32), tf.constant(1)) # 1
练习
让我们应用所学到的内容,转换一个算法到 TensorFlow。下面是一段简单的用除和减的算法。把这个算法从 Python 转换到 TensorFlow 并把结果打印出来。你可以用 tf.constant()
来对 10
、2
和 1
赋值。
Start Quiz:
# Solution is available in the other "solution.py" tab
import tensorflow as tf
# TODO: Convert the following to TensorFlow:
x = 10
y = 2
z = x/y - 1
# TODO: Print z from a session
# Quiz Solution
# Note: You can't run code in this tab
import tensorflow as tf
# TODO: Convert the following to TensorFlow:
x = tf.constant(10)
y = tf.constant(2)
z = tf.subtract(tf.divide(x,y),tf.cast(tf.constant(1), tf.float64))
# TODO: Print z from a session
with tf.Session() as sess:
output = sess.run(z)
print(output)